﻿using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure.Dispatcher
{
    /// <summary>
    /// 调度总线
    /// </summary>
    public class DispatcherBus
    {
        /// <summary>
        /// 任务容器
        /// </summary>
        static BlockingCollection<DispatcherTask> TaskContainer;

        static DispatcherBus() {
            TaskContainer = new BlockingCollection<DispatcherTask>();
            var taskLimitNumber = 1;
            for (var i = 0; i < taskLimitNumber; i++) {
                Task.Factory.StartNew(() =>
                {
                    RunTask();
                });
            }
        }

        static void RunTask() {
            foreach (var task in TaskContainer.GetConsumingEnumerable())
            {
                try
                {
                    task.Run();
                }
                catch (Exception ex) { 
                    
                }
            }
        }

        /// <summary>
        /// 添加调度任务
        /// </summary>
        /// <param name="task"></param>
        /// <returns></returns>
        public static Boolean AddTask(DispatcherTask task) {
            return TaskContainer.TryAdd(task);
        }
    }
}
